'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url admin/auto_run/pub/compute_adminmrsj_data 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		const db = uniCloud.database();
		const $ = db.command.aggregate;
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			_
		} = util;
		let {
			uid,
			user_id,
			role,
			username,
			nickname,
			middleman_id,
			item,
			todayStart,
			todayEnd,
			last_StartTime,
			last_EndTime,
			yesterday
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------

		//admin 数据 开始
		if (role.includes('admin')) {
			//查询昨日新增用户数
			res.num = await vk.baseDao.count({
				dbName: "uni-id-users",
				whereJson: {
					register_date: _.and(_.gt(last_StartTime), _.lt(last_EndTime))
				}
			});

			//查询昨日新用户充值总金额
			res.new_users_moneysum = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					pay_status: 1,
					user_register_date: _.and(_.gt(last_StartTime), _.lt(last_EndTime)),
					_add_time: _.and(_.gt(last_StartTime), _.lt(last_EndTime))
				}
			});


			//====查询充值订单里，昨天一共有多少个新付费用户====
			// 执行聚合查询,昨天充值新用户人数（注册时间是昨天）。
			let newUsers_payNumber = await db.collection('a_recharge')
				.aggregate()
				.match({
					_add_time: _.and(_.gt(last_StartTime), _.lt(last_EndTime)),
					user_register_date: _.and(_.gt(last_StartTime), _.lt(last_EndTime)),
					user_id: db.command.exists(true),
					pay_status: 1
				})
				.group({
					_id: null,
					user_count: $.addToSet('$user_id')
				})
				.end()
			//获取新付费用户数量
			res.newUsers_payNumber = newUsers_payNumber.data.length ? newUsers_payNumber.data[0].user_count
				.length : 0
			//====计算新付费用户结束====


			//====查询充值订单里，昨天一共有多少个付费用户====
			// 执行聚合查询,昨日充值人数
			let newRows_userid = await db.collection('a_recharge')
				.aggregate()
				.match({
					_add_time: _.and(_.gt(last_StartTime), _.lt(last_EndTime)),
					user_id: db.command.exists(true),
					pay_status: 1
				})
				.group({
					_id: null,
					user_count: $.addToSet('$user_id')
				})
				.end()
			//获取新付费用户数量
			res.Users_payNumber = newRows_userid.data.length ? newRows_userid.data[0].user_count.length : 0
			//====计算今日付费用户结束====


			//查询昨日充值笔数 
			res.today_recharges_Number = await vk.baseDao.count({
				dbName: "a_recharge",
				whereJson: {
					pay_status: 1,
					_add_time: _.and(_.gt(last_StartTime), _.lt(last_EndTime))
				}
			});

			//查询昨日充值总金额
			res.today_Recharge_amount = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					pay_status: 1,
					_add_time: _.and(_.gt(last_StartTime), _.lt(last_EndTime))
				}
			});
			
			//复充金额(用户多次充值订单的总金额)
			let today_repeat_amount = await db.collection('a_recharge').aggregate()
				.match({
					pay_status: 1,
					_add_time: _.and(_.gt(last_StartTime), _.lt(last_EndTime))
				})
				.group({
					_id: '$user_id',
					count: {
						$sum: 1
					},
					total_amount: {
						$sum: '$shifu_amount'
					}
				})
				.match({
					count: {
						$gt: 1
					}
				})
				.group({
					_id: null,
					grand_total: {
						$sum: '$total_amount'
					}
				})
				.project({
					_id: 0,
					grand_total: 1
				})
				.end();
			if (today_repeat_amount.data.length != 0) {
				res.today_repeat_amount = today_repeat_amount.data[0].grand_total
			}
			

			//复充人数
			let orderCollection = db.collection('a_recharge');
			let numberRePurchasers = await orderCollection.aggregate()
				.match({
					pay_status: 1,
					_add_time: _.and(_.gt(last_StartTime), _.lt(last_EndTime))
				})
				.group({
					_id: '$user_id',
					count: {
						$sum: 1
					}
				})
				.match({
					count: {
						$gt: 1
					}
				})
				.count('distinctBuyerCount')
				.end()
			// console.log("numberRePurchasers=", numberRePurchasers);
			res.today_repeat_user = numberRePurchasers.affectedDocs;

			// 计算数据
			res.new_users_ffl = res.Users_payNumber / res.num; //新用户付费率
			res.new_users_rjcz = res.new_users_moneysum / res.num; //新用户人均充值
			res.today_bdj = res.today_Recharge_amount / res.today_recharges_Number; //笔单价
			res.new_users_payup = res.new_users_moneysum / res.Users_payNumber; //新用户付费up值
			res.new_users_up = res.new_users_moneysum / res.num; //新用户up值
			res.new_users_fcl = res.today_repeat_user / res.Users_payNumber; //复冲率

		}
		//admin数据结束 -------------------------------------------------------------

		//代理商数据开始 -------------------------------------------------------------
		if (role.includes('agent')) {
			//查询昨日新增用户数
			res.num = await vk.baseDao.count({
				dbName: "uni-id-users",
				whereJson: {
					invite_code: user_id,
					register_date: _.and(_.gt(last_StartTime), _.lt(last_EndTime))
				}
			});
			//查询昨日新用户充值总金额
			res.new_users_moneysum = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					invite_code: user_id,
					pay_status: 1,
					_add_time: _.and(_.gt(last_StartTime), _.lt(last_EndTime)),
					user_register_date: _.and(_.gt(last_StartTime), _.lt(last_EndTime))
				}
			});
			//====查询充值订单里，一共有多少个新付费用户====

			let jrczrs = await db.collection('a_recharge')
				.aggregate()
				.match({
					invite_code: user_id,
					pay_status: 1, //状态为支付完成
					user_register_date: _.and(_.gt(last_StartTime), _.lt(last_EndTime)),
					_add_time: _.and(_.gt(last_StartTime), _.lt(last_EndTime))
				})
				.group({
					_id: null,
					user_count: $.addToSet('$user_id')
				})
				.end()
			res.newUsers_payNumber = jrczrs.data.length ? jrczrs.data[0].user_count.length : 0
			//====计算新付费用户结束====


			//====查询充值订单里，一共有多少个付费用户====
			//查询一共有多少个符合条件的充值订单，条件为：已支付+记录时间为昨天天
			let todayRechargeUsers = await vk.baseDao.select({
				dbName: "a_recharge", // 表名
				getCount: true, // 是否需要同时查询满足条件的记录总数量，默认false
				getMain: false, // 是否只返回rows数据，默认false
				pageIndex: 1, // 当前第几页
				pageSize: -1, // 每页条数
				// 只要user_id字段
				fieldJson: {
					user_id: true
				},
				whereJson: {
					invite_code: user_id,
					pay_status: 1, //状态为支付完成
					_add_time: _.and(_.gt(last_StartTime), _.lt(last_EndTime)),
					user_register_date: _.and(_.gt(last_StartTime), _.lt(last_EndTime))
				}
			});
			//从数组中提取user_id字段形式新的数组
			let rows_userid = vk.pubfn.arrayObjectGetArray(todayRechargeUsers.rows, "user_id");
			//一个用户可能充值多次，因此需要去重
			var newRows_userid = [...new Set(rows_userid)]; //利用了Set结构不能接收重复数据的特点进行去重
			// console.log("newRows.length=", newRows_userid.length);
			//获取新付费用户数量
			res.Users_payNumber = newRows_userid.length
			//====计算今日付费用户结束====


			//查询今日充值笔数 
			res.today_recharges_Number = await vk.baseDao.count({
				dbName: "a_recharge",
				whereJson: {
					invite_code: user_id,
					pay_status: 1,
					_add_time: _.and(_.gt(last_StartTime), _.lt(last_EndTime))
				}
			});

			//查询今日充值总金额
			res.today_Recharge_amount = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					invite_code: user_id,
					pay_status: 1,
					_add_time: _.and(_.gt(last_StartTime), _.lt(last_EndTime))
				}
			});
			//复充金额(用户多次充值订单的总金额)
			let today_repeat_amount = await db.collection('a_recharge').aggregate()
				.match({
					invite_code: user_id,
					pay_status: 1,
					_add_time: _.and(_.gt(last_StartTime), _.lt(last_EndTime))
				})
				.group({
					_id: '$user_id',
					count: {
						$sum: 1
					},
					total_amount: {
						$sum: '$shifu_amount'
					}
				})
				.match({
					count: {
						$gt: 1
					}
				})
				.group({
					_id: null,
					grand_total: {
						$sum: '$total_amount'
					}
				})
				.project({
					_id: 0,
					grand_total: 1
				})
				.end();
			if (today_repeat_amount.data.length != 0) {
				res.today_repeat_amount = today_repeat_amount.data[0].grand_total
			}

			//复充人数
			let orderCollection = db.collection('a_recharge');
			let numberRePurchasers = await orderCollection.aggregate()
				.match({
					invite_code: user_id,
					pay_status: 1,
					_add_time: _.and(_.gt(last_StartTime), _.lt(last_EndTime))
				})
				.group({
					_id: '$user_id',
					count: {
						$sum: 1
					}
				})
				.match({
					count: {
						$gt: 1
					}
				})
				.count('distinctBuyerCount')
				.end()
			// console.log("numberRePurchasers=", numberRePurchasers);
			res.today_repeat_user = numberRePurchasers.affectedDocs;

			// 计算数据
			res.new_users_ffl = res.Users_payNumber / res.num; //新用户付费率
			res.new_users_rjcz = res.new_users_moneysum / res.num; //新用户人均充值
			res.today_bdj = res.today_Recharge_amount / res.today_recharges_Number; //笔单价
			res.new_users_payup = res.new_users_moneysum / res.Users_payNumber; //新用户付费up值
			res.new_users_up = res.new_users_moneysum / res.num; //新用户up值
			res.new_users_fcl = res.today_repeat_user / res.Users_payNumber; //复冲率
		}
		//代理商数据结束 -------------------------------------------------------------


		//机构数据开始 -------------------------------------------------------------
		if (role.includes('middleman')) {
			//查询昨日新增用户数
			res.num = await vk.baseDao.count({
				dbName: "uni-id-users",
				whereJson: {
					middleman_id: user_id,
					register_date: _.and(_.gt(last_StartTime), _.lt(last_EndTime))
				}
			});
			//查询昨日新用户充值总金额
			res.new_users_moneysum = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					middleman_id: user_id,
					pay_status: 1,
					_add_time: _.and(_.gt(last_StartTime), _.lt(last_EndTime)),
					user_register_date: _.and(_.gt(last_StartTime), _.lt(last_EndTime))
				}
			});



			//====查询充值订单里，昨天一共有多少个新付费用户====
			let conditions1 = {
				middleman_id: user_id,
				_add_time: _.and(_.gt(last_StartTime), _.lt(last_EndTime)),
				user_register_date: _.and(_.gt(last_StartTime), _.lt(last_EndTime)),
				user_id: db.command.exists(true),
				pay_status: 1
			}
			// 执行聚合查询,今日充值新用户人数（注册时间是今天）。
			let newUsers_payNumber = await db.collection('a_recharge')
				.aggregate()
				.match(conditions1)
				.group({
					_id: null,
					user_count: $.addToSet('$user_id')
				})
				.end()
			//获取新付费用户数量
			res.newUsers_payNumber = newUsers_payNumber.data.length ? newUsers_payNumber.data[0].user_count
				.length : 0
			//====计算新付费用户结束====


			//====查询充值订单里，昨天天一共有多少个付费用户====
			// 查询条件
			let conditions2 = {
				middleman_id: user_id,
				_add_time: _.and(_.gt(last_StartTime), _.lt(last_EndTime)),
				user_id: db.command.exists(true),
				pay_status: 1
			}
			// 执行聚合查询,今日充值人数
			let newRows_userid = await db.collection('a_recharge')
				.aggregate()
				.match(conditions2)
				.group({
					_id: null,
					user_count: $.addToSet('$user_id')
				})
				.end()
			//获取新付费用户数量
			res.Users_payNumber = newRows_userid.data.length ? newRows_userid.data[0].user_count.length : 0
			//====计算今日付费用户结束====


			//查询昨日充值笔数 
			res.today_recharges_Number = await vk.baseDao.count({
				dbName: "a_recharge",
				whereJson: {
					middleman_id: user_id,
					pay_status: 1,
					_add_time: _.and(_.gt(last_StartTime), _.lt(last_EndTime))
				}
			});

			//查询昨日充值总金额
			res.today_Recharge_amount = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					middleman_id: user_id,
					pay_status: 1,
					_add_time: _.and(_.gt(last_StartTime), _.lt(last_EndTime))
				}
			});
			//复充金额(用户多次充值订单的总金额)
			let today_repeat_amount = await db.collection('a_recharge').aggregate()
				.match({
					middleman_id: user_id,
					pay_status: 1,
					_add_time: _.and(_.gt(last_StartTime), _.lt(last_EndTime))
				})
				.group({
					_id: '$user_id',
					count: {
						$sum: 1
					},
					total_amount: {
						$sum: '$shifu_amount'
					}
				})
				.match({
					count: {
						$gt: 1
					}
				})
				.group({
					_id: null,
					grand_total: {
						$sum: '$total_amount'
					}
				})
				.project({
					_id: 0,
					grand_total: 1
				})
				.end();
			if (today_repeat_amount.data.length != 0) {
				res.today_repeat_amount = today_repeat_amount.data[0].grand_total
			}

			//复充人数
			let orderCollection = db.collection('a_recharge');
			let numberRePurchasers = await orderCollection.aggregate()
				.match({
					middleman_id: user_id,
					pay_status: 1,
					_add_time: _.and(_.gt(last_StartTime), _.lt(last_EndTime))
				})
				.group({
					_id: '$user_id',
					count: {
						$sum: 1
					}
				})
				.match({
					count: {
						$gt: 1
					}
				})
				.count('distinctBuyerCount')
				.end()
			// console.log("numberRePurchasers=", numberRePurchasers);
			res.today_repeat_user = numberRePurchasers.affectedDocs;

			// 计算数据
			res.new_users_ffl = res.Users_payNumber / res.num; //新用户付费率
			res.new_users_rjcz = res.new_users_moneysum / res.num; //新用户人均充值
			res.today_bdj = res.today_Recharge_amount / res.today_recharges_Number; //笔单价
			res.new_users_payup = res.new_users_moneysum / res.Users_payNumber; //新用户付费up值
			res.new_users_up = res.new_users_moneysum / res.num; //新用户up值
			res.new_users_fcl = res.today_repeat_user / res.Users_payNumber; //复冲率

		}
		//机构数据结束 -------------------------------------------------------------
		// console.log("得到的数据", res);

		//添加平台昨日总数据到数据库
		let add_datas = await db.collection('a_datas').add({
			//此处的变量名延用了看板的变量名
			today_repeat_user: res.today_repeat_user, //复冲人数
			today_repeat_amount: res.today_repeat_amount, //复冲金额
			today_Recharge_amount: res.today_Recharge_amount, //查询昨日充值总金额
			today_recharges_Number: res.today_recharges_Number, //查询昨日充值笔数
			Users_payNumber: res.Users_payNumber, //获取新付费用户数量
			new_users_moneysum: res.new_users_moneysum, //查询昨日新用户充值总金额
			num: res.num, //查询昨日新增用户数
			new_users_ffl: res.new_users_ffl, //新用户付费率
			new_users_rjcz: res.new_users_rjcz, //新用户人均充值
			today_bdj: res.today_bdj, //笔单价
			new_users_payup: res.new_users_payup, //新用户付费up值
			new_users_up: res.new_users_up, //新用户up值
			new_users_fcl: res.new_users_fcl, //复冲率
			user_id: user_id, //用户ID 此处的user_id就是用户表里的id
			username: username, //用户名
			nickname: nickname, //用户昵称
			middleman_id: middleman_id || "", //上级代理商id
			role: role, //用户职位 代理商 机构 admin
			type: 16, //0是平台总数据，1是账号级数据，2是链接级数据，3机构数据
			remark: "type=16,是看板每日数据",
			date: yesterday,
			date_time: last_StartTime, //添加一个记录日期的时间戳，方便后面使用筛选日期功能
			_add_time: new Date().getTime(),
			_add_time_str: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss")
		})



		// 业务逻辑结束-------------------------------------------------------------
		return res;
	}
}